package com.jar.springbootsecuritydemo.config;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 授权进入点 【授权失败处理类】
 * 这里根据业务返回自己的Response类
 */
@Component
public class AuthorizationDeniedHandle implements AccessDeniedHandler {
    /**
     * 重写 handle 方法
     * @param request  请求
     * @param response 相应
     * @param e 异常
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException {
        Map<String, Object> result = new HashMap<>(3);
        String msg = StringUtils.format("请求访问：{}，访问失败，没有权限访问系统资源", request.getRequestURI());
        response.setStatus(200);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        result.put("code", 401);
        result.put("msg", msg);
        result.put("data", "没有权限");
        response.getWriter().write(JSONObject.toJSONString(result));
    }
}